//
//  FamilyEditViewController.m
//  FD
//
//  Created by Yasin on 2018/10/24.
//  Copyright © 2018 ZhiYuan Network. All rights reserved.
//  编辑家庭成员

#import "FamilyEditViewController.h"
#import "AddBirthViewController.h"

//view
#import "BRDatePickerView.h"
#import "AddBirthHeaderView.h"
#import "XLAlertView.h" //删除弹框

//model
#import "FamilyModel.h"

@interface FamilyEditViewController ()<UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate>

/**tv*/
@property (nonatomic,  strong) UITableView *tv;
/**表头*/
@property (nonatomic, strong) AddBirthHeaderView *headerView;
/**表尾 里面有一个完成按钮*/
@property (nonatomic,  strong) UIView *footerView;

/**时间戳*/
@property (nonatomic,  strong) NSNumber *timestamp;
@end

@implementation FamilyEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([NSString rb_ChineseLanguage]) {
        self.navigationItem.title = @"修改成员生日";
    }else {
        self.navigationItem.title = @"Edit Member's Birthday";
    }
    
    [self setupView];
    
    //赋值
    if (self.model) {
        self.headerView.pleaseInputNameTF.text = self.model.memberName;
        self.headerView.pleaseBirthDayLb.text = self.model.birthdayStr;
        //给时间戳赋值
        self.timestamp = self.model.memberBirthday;
    }
}

- (void)setupView {
    
    //导航条
    //右侧删除按钮
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn setImage:[UIImage imageNamed:@"del"] forState:(UIControlStateNormal)]; //删除按钮
    [btn addTarget:self action:@selector(removeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    
    //tv
    self.tv.frame = self.view.bounds;
    [self.view addSubview:self.tv];

    
    //表头 & 表尾
    self.tv.tableHeaderView = self.headerView;
    
    self.footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100); //设置frame
    self.tv.tableFooterView = self.footerView;
}

- (void)removeAction:(UIButton *)btn {
    [self delecteSureAlert]; //弹框
}

- (void)delecteSureAlert {
    NSString *tsStr = NSLocalizedString(L_Pay_Tips, @"提示");
    NSString *qdStr = NSLocalizedString(Sure, @"确定");
    NSString *qxStr = NSLocalizedString(Cancel, @"取消");
    
    
    XLAlertView *deleteAlertView = [[XLAlertView alloc] initWithTitle:tsStr message:@"是否删除该成员生日信息?" sureBtn:qdStr cancleBtn:qxStr];
    [deleteAlertView showXLAlertView];
    deleteAlertView.resultIndex = ^(NSInteger index) {
        if (index==2) {
            [self requestDelete]; //调接口
        }
    };
}




- (void)requestDelete {
    [FDHttpAPi requestUserFamilRemoveMemberId:self.model.memberid successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [self.navigationController popViewControllerAnimated:YES];
            //原路返回 并属性数据
        }else { //toast
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        
    }];
}

#pragma mark  - 代理
- (UITableView *)tv {
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        _tv.delegate = self;
        _tv.dataSource = self;
        //注册cell
        
        [_tv registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    }
    return _tv;
}

- (UIView *)footerView {
    if (!_footerView) {
        _footerView = [UIView new];
        //创建一个按钮
        NSString *wcStr = @"Confirm";
        if ([NSString rb_ChineseLanguage]) {
            wcStr = @"完成";
        }
        UIButton *btn = [UIButton createFastRedBtnRadius:5 target:self action:@selector(clickComplementationAction:) title:wcStr];
        
        [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        btn.backgroundColor = kMainRedColor;
        btn.frame = CGRectMake(26, 20, self.view.bounds.size.width - 52, 40);
        [_footerView addSubview:btn]; //添加
    }
    return _footerView;
}

- (AddBirthHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[AddBirthHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
        
        FDWeakSelf;
        //事件回调
        _headerView.headerViewSelectBirthDayBlock = ^{
            //限制日期,比允许瞎几把该,会导致直接奔溃。
            NSDate *minDate = [NSDate br_setYear:1900 month:1 day:1];
            NSDate *maxDate = [NSDate date];
            
            //2019-2-26 弹出日期后默认显示的时间
            NSString *dv = weakSelf.model.birthdayStr;
            if ([NSString isEmptyString:dv]) {
                dv = @"2000-1-1";
            }
            
            [BRDatePickerView showDatePickerWithTitle:@"出生日期" dateType:BRDatePickerModeYMD defaultSelValue:dv minDate:minDate maxDate:maxDate isAutoSelect:YES themeColor:nil resultBlock:^(NSString *selectValue) {
                
                //wea
                weakSelf.headerView.pleaseBirthDayLb.text = selectValue;
                
                NSNumber *timeStamp = [NSString timeStampFromDateStr:selectValue];
                
                weakSelf.timestamp = timeStamp; //保存时间戳
            } cancelBlock:^{
                NSLog(@"点击了背景或取消按钮");
            }];
        };
    }
    return _headerView;
}

- (void)clickComplementationAction:(UIButton *)btn {
    
    NSString *name = self.headerView.pleaseInputNameTF.text;
    
    if ([NSString isEmptyString:name]) {
        [JRToast showWithText:NSLocalizedString(ToastNameCannotKong, @"姓名不能为空")];
        return;
    }
    if ([NSString isEmptyString:[NSString stringWithFormat:@"%@",self.timestamp]]) {
        [JRToast showWithText:NSLocalizedString(ToastBirthdayCannotKong, @"生日不能为空")];
        return;
    }
    
    //完成调接口
    [FDHttpAPi requestUserFamilUpdateName:name birthdaystamp:self.timestamp memberId:self.model.memberid successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [JRToast showWithText:NSLocalizedString(ToastModifySuccess, @"修改成功")];
            //原路返回
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"更新成员生日请求失败:%@",[error localizedDescription]);
    }];
}

- (void)handlerTextFieldSelect:(UITextField *)textField {
    if (textField.tag == 1) {
        NSDate *minDate = [NSDate br_setYear:1900 month:3 day:12];
        NSDate *maxDate = [NSDate date];
        
        NSString *csrqStr = NSLocalizedString(DateOfBirth, @"出生日期");

        [BRDatePickerView showDatePickerWithTitle:csrqStr dateType:BRDatePickerModeYMD defaultSelValue:textField.text minDate:minDate maxDate:maxDate isAutoSelect:YES themeColor:nil resultBlock:^(NSString *selectValue) {
            
            textField.text = selectValue;
            
            //时间戳
            NSNumber *timestamp = [NSString timeStampFromDateStr:selectValue];
            //保存时间戳
            self.timestamp = timestamp;
            
        } cancelBlock:^{
            FDLog(@"点击了背景或取消按钮");
        }];
    }
}


#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
    return cell;
}


//字符串转时间戳 如：2017-4-10 17:15:10
- (NSString *)getTimeStrWithString:(NSString *)str{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
    NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
    NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
    return timeStr;
}

@end

